package com.wushijia.java8.concurrent;

import static java.util.concurrent.Executors.newFixedThreadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.locks.StampedLock;

/**
 * 1、如果当前值是零，我们希望将其赋值为23。我们首先需要将读锁转换为写锁，来避免打破其它线程潜在的并发访问
 *
 * 2、tryConvertToWriteLock()的调用不会阻塞，但是可能会返回为零的标记，表示当前没有可用的写锁。这种情况下，我们调用writeLock()来阻塞当前线程，直到有可用的写锁
 *
 * @author Benjamin Winterberg
 */
public class Lock6 {

  private static int count = 0;

  public static void main(String[] args) {
    ExecutorService executor = newFixedThreadPool(2);

    StampedLock lock = new StampedLock();

    executor.submit(() -> {
      long stamp = lock.readLock();
      try {
        if (count == 0) {
          stamp = lock.tryConvertToWriteLock(stamp);
          if (stamp == 0L) {
            System.out.println("Could not convert to write lock");
            stamp = lock.writeLock();
          }
          count = 23;
        }
        System.out.println(count);
      } finally {
        lock.unlock(stamp);
      }
    });

    ConcurrentUtils.stop(executor);
  }

}
